require 'utils'

$pick_property = PropertyTemplate.find(30)

def find_map(name)
  begin
    return find_map_by_name(name)
  rescue Exception => e
    puts e
    return nil
  end
end

def check_property(item, map)
  properties = item.properties
  return nil if properties.nil?
  return nil if properties.empty?
  properties.split(",").each do |property_id|
    property = ItemProperty.find(property_id)
    next unless property.template_id == $pick_property.id
    return property if property.reserved1 == map.id
  end
  return nil
end

def add_property_to_item(property, item)
  property_id = property.id.to_s
  if item.properties.nil?
    item.properties = property_id
  elsif item.properties.empty?
    item.properties = property_id
  else
    old = item.properties
    item.properties = "#{old},#{property_id}"
  end
  item.save
end

def add_item_to_map(item, map)
  begin
    property = check_property(item, map)
    return unless property.nil?

    property = ItemProperty.new
    property.template_id = $pick_property.id
    property.item_id = item.id
    property.reserved1 = map.id
    property.reserved4 = map.japaness_name
    desc = $pick_property.description
    desc.gsub!(/\$\(r4\)/, map.japaness_name)
    property.description = desc
    property.save
  
    add_property_to_item(property, item)
  rescue Exception => e
    raise "#{e} with item:#{item.id}-#{item.japaness_name}"
  end
end

File.open('templates/drop.txt', 'r') do |file|
  while line = file.gets
    line.chop!
    strs = line.split("\t")
    map = find_map(strs[0])
    next if map.nil?
    
    items = strs[1].split(",")
    items.each do |item_name|
      begin
        item = find_item_by_name(item_name)
        add_item_to_map(item, map)
      rescue Exception => e
        puts "#{e} in map: #{map.id}-#{map.japaness_name}"
      end
    end
  end
end
